package cn.hahah.module.blog.app;


import cn.hutool.dfa.WordTree;
import org.springframework.stereotype.Component;
import jakarta.annotation.PostConstruct;

import java.util.HashSet;
import java.util.Set;
import java.util.regex.Pattern;
import org.springframework.core.io.ClassPathResource;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;

/**
 * 敏感词检测工具类
 * 基于 Hutool 5.8.35 的 WordTree 实现
 */
@Component
public class SensitiveWordUtil {

    // 敏感词白名单（即使包含敏感词也不处理）
    private final Set<String> whiteList = new HashSet<>();

    // Hutool 的 WordTree 实现敏感词检测
    private final WordTree wordTree = new WordTree();

    /**
     * 初始化敏感词库并编译为正则表达式
     */
    @PostConstruct
    public void init() {
        // 加载敏感词库（从classpath下的sensitive-words.txt文件）
        try (InputStream inputStream = new ClassPathResource("sensitive-words.txt").getInputStream();
             BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
            String line;
            while ((line = reader.readLine()) != null) {
                if (!line.trim().isEmpty()) {
                    wordTree.addWord(line.trim());
                }
            }
        } catch (IOException e) {
            throw new RuntimeException("加载敏感词库失败", e);
        }

        // 初始化白名单
        whiteList.addAll(Arrays.asList("清华大学", "北京大学"));
    }

    /**
     * 检测文本中是否包含敏感词
     * @param text 待检测文本
     * @return true-包含敏感词，false-不包含
     */
    public boolean containsSensitiveWord(String text) {
        if (text == null || text.isEmpty()) {
            return false;
        }

        // 先检查白名单
        if (whiteList.stream().anyMatch(text::contains)) {
            return false;
        }

        return !wordTree.matchAll(text).isEmpty();
    }

}